package com.springcloud.zuul.controller;

import com.springcloud.zuul.common.annotation.SysLog;
import com.springcloud.zuul.common.constant.ServiceCode;
import com.springcloud.zuul.common.utlis.JsonResult;
import com.springcloud.zuul.common.utlis.R;
import com.springcloud.zuul.common.validator.Assert;
import com.springcloud.zuul.common.validator.ValidatorUtils;
import com.springcloud.zuul.common.validator.group.UpdateGroup;
import com.springcloud.zuul.entity.SysUserEntity;
import com.springcloud.zuul.form.PasswordForm;
import com.springcloud.zuul.service.SysConfigService;
import com.springcloud.zuul.service.SysUserRoleService;
import com.springcloud.zuul.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 系统用户
 */
@RestController
@RequestMapping("/sys/user")
@Api(tags = "系统用户")
public class SysUserController extends AbstractController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    SysConfigService sysConfigService;

    /**
     * Description:所有用户列表
     * @author zhlu
     * @date 2020/1/6 11:21 上午
     * @param params
     * @return com.springcloud.zuul.common.utlis.JsonResult
     */
    @GetMapping("/list")
    @RequiresPermissions("sys:user:list")
    @ApiOperation(notes = "所有用户列表",value = "所有用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName",value = "用户名称",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "pageNum",value = "第几页",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "pageSize",value = "每页多少条",required = true,dataType = "String",paramType = "query")
    })
    public JsonResult list(@RequestParam Map<String, Object> params) {
        //手动设置超级管理员,拥有最高权限
        List<String> list = Arrays.asList(sysConfigService.getValue("superAdmin").split(","));
        //只有超级管理员，才能查看所有管理员列表
        if (!list.contains(getUserId())) {
            params.put("insby", getUserId());
        }
        return JsonResult.success(sysUserService.queryPage(params));
    }

    /**
     * Description:修改登录用户密码
     * @author zhlu
     * @date 2020/1/6 1:40 下午
     * @param form
     * @return com.springcloud.zuul.common.utlis.JsonResult
     */
    @SysLog("修改密码")
    @PostMapping("/password")
    @ApiOperation(notes = "修改登录用户密码",value = "修改登录用户密码")
    public JsonResult password(@RequestBody PasswordForm form) {
        Assert.isBlank(form.getNewPassword(), "新密码不为能空");

        //sha256加密
        String password = new Sha256Hash(form.getPassword(), getUser().getSalt()).toHex();
        //sha256加密
        String newPassword = new Sha256Hash(form.getNewPassword(), getUser().getSalt()).toHex();

        //更新密码
        boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
        if (!flag) {
            return JsonResult.error(ServiceCode.PASSWORD_IS_INCORRECT);
        }

        return JsonResult.success();
    }

    /**
     * Description:获取登录的用户信息
     * @author zhlu
     * @date 2020/1/6 2:13 下午
     * @param
     * @return com.springcloud.zuul.common.utlis.JsonResult
     */
    @GetMapping("/info")
    @ApiOperation(notes = "获取登录的用户信息",value = "获取登录的用户信息")
    public JsonResult info() {
        return JsonResult.success(getUser());
    }

    /**
     * 用户信息
     */
    @GetMapping("/info/{userId}")
    @RequiresPermissions("sys:user:info")
    public R info(@PathVariable("userId") String userId) {
        SysUserEntity user = sysUserService.getById(userId);

        //获取用户所属的角色列表
//        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
//        user.setRoleIdList(roleIdList);

        return R.ok().put("user", user);
    }

    /**
     * 保存用户
     */
    @SysLog(value = "保存用户", type = 2)
    @PostMapping("/save")
    @ApiOperation(notes = "保存用户", value = "保存用户")
    public JsonResult save(@RequestBody SysUserEntity user) {
        return sysUserService.saveUser(user);
    }

    /**
     * 修改用户
     */
    @SysLog("修改用户")
    @PostMapping("/update")
    @RequiresPermissions("sys:user:update")
    public R update(@RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user, UpdateGroup.class);

        sysUserService.update(user);

        return R.ok();
    }

    /**
     * 删除用户
     */
    @SysLog("删除用户")
    @PostMapping("/delete")
    @RequiresPermissions("sys:user:delete")
    public R delete(@RequestBody Long[] userIds) {
        if (ArrayUtils.contains(userIds, 1L)) {
            return R.error("系统管理员不能删除");
        }

        if (ArrayUtils.contains(userIds, getUserId())) {
            return R.error("当前用户不能删除");
        }

        sysUserService.deleteBatch(userIds);

        return R.ok();
    }
}
